import { Controller, Get, Action, Middlewares } from 'koa-decorator-helpers'
import * as api from '~/libs/wx/api'
import { getComponentAccessToken } from '~/data/token'
import { RouterContext } from '@koa/router'
import koaBody from 'koa-body'

/**
 * 第三方平台授权
 */
@Controller({ prefix: '/authorize' })
@Middlewares([koaBody()])
export class Authorize {
    /**
     * 第三方平台授权起始页
     */
    @Get('/:component_app_id')
    async start(ctx: RouterContext) {
        const success = (url: string) => {
            ctx.type = 'text/html; charset=utf-8'
            return `<html><body><script>location.replace(${JSON.stringify(url)})</script></body></html>`
        }
        const fail = (msg: string) => {
            ctx.type = 'text/html; charset=utf-8'
            return `<html><body>${msg}</body></html>`
        }

        //生成预授权码
        const component_access_token = await getComponentAccessToken(ctx.params.component_app_id)
        if (!component_access_token) {
            return fail('无效的component_app_id')
        }

        const ret_auth_code = await api.component.getPreAuthCode(ctx.params.component_app_id, component_access_token)

        //const redirect_uri = 'https://customer.bjxjcm.cn/wx/authorize/success'
        const redirect_uri = new URL('/authorize/success', 'https://' + ctx.host).href

        return success(
            `https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&no_scan=1&component_appid=${encodeURIComponent(
                ctx.params.component_app_id,
            )}&pre_auth_code=${encodeURIComponent(ret_auth_code.pre_auth_code)}&redirect_uri=${encodeURIComponent(
                redirect_uri,
            )}&auth_type=1#wechat_redirect`,
        )
    }

    @Action('/success')
    success() {
        return '授权成功'
    }
}
